var BigUtil = {
    isEmpty: function (val) {
        return val == undefined || val == '' || val == null;
    },
    random: function (min, max) {
        return min + Math.floor(Math.random() * (max - min + 1));
    },
    attr: function (jq, attribute, defaultValue) {
        if (BigUtil.isEmpty(jq.attr(attribute))) {
            return defaultValue;
        }
        return jq.attr(attribute);
    },
    hasAttr: function (jq, attr) {
        if (jq.attr(attr) == undefined) {
            return false;
        }
        return true;
    },
    appendQueryString : function (url, queryString) {
    	if (url.indexOf('?') > 0) {
    		return url + "&" + queryString;
    	}
    	return url + "?" + queryString;
    },
    getObject: function (selector, defaultSelector) {
        if (BigUtil.isEmpty(selector)) {
            return $(defaultSelector);
        }
        if (typeof (selector) == 'string') {
            return $(selector);
        }
        return selector;
    },
    stringToDate: function (str) {
        var tempStrs = str.split(" ");
        var dateStrs = tempStrs[0].split("-");
        var year = parseInt(dateStrs[0], 10);
        var month = parseInt(dateStrs[1], 10) - 1;
        var day = parseInt(dateStrs[2], 10);
        var timeStrs = tempStrs[1].split(":");
        var hour = parseInt(timeStrs [0], 10);
        var minute = parseInt(timeStrs[1], 10);
        var second = parseInt(timeStrs[2], 10);
        var date = new Date(year, month, day, hour, minute, second);
        return date;
    },
    //时间日期转换成string
    dateToString: function (d, value) {
        function dFormat(i) {
            return i < 10 ? "0" + i.toString() : i;
        }

        if (value == "yyyy-MM-dd") {
            var ar_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()];
            for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i]);
            return ar_date.join('-');
        }
        var ar_date = [d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()];
        for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i]);
        return ar_date.slice(0, 3).join('-') + ' ' + ar_date.slice(3).join(':');
    },
    parseData: function (jqObj, prefix) {
        var appData = {};
        if (jqObj.length == 0) {
            return appData;
        }
        // 获取参数
        $.each(jqObj[0].attributes, function () {
            if (this.name.startsWith(prefix)) {
                var key = this.name.substring(prefix.length);
                appData[key] = this.value;
            }
        });
        return appData;
    },
    clone: function (target, source, deep) {
        if (deep == true) {
            $.extend(true, target, source);
        } else {
            $.extend(target, source);
        }
        return target;
    },
    mergeFormData: function (formData, data) {
        for (var key in data) {
            for (var i = formData.length - 1; i >= 0; i--) {
                if (formData[i].name == key) {
                    formData.splice(i, 1);
                }
            }
            formData.push({name: key, value: data[key]});
        }
        return formData;
    },
    createTab: function (options) {
        // 新增tab的index
        var index = parseInt($('div[id^=divBigContentTab_]:last').attr('id').split('_')[1]) + 1;
        // tab-header
        var tabsHeader = $('#divBigContent .nav-tabs');
        tabsHeader.find('li').removeClass('active');
        var headerHtml = ['<li class="active">',
            '<a href="#divBigContentTab_' + index + '" data-toggle="tab">',
            '<span>' + options.title + '</span>',
            '<span class="fa fa-times btn btn-xs pull-right"></span>',
            '</a>',
            '</li>'].join('');
        $(headerHtml).appendTo(tabsHeader).find('span.fa-times').click(function () {
            BigUtil.closeTab($(this));
        });

        // tab-body
        var tabs = $('#divBigContent .tab-content');
        tabs.find('.tab-pane').removeClass('active');
        var tabHtml = '<div class="tab-pane active" id="divBigContentTab_' + index + '" />';
        return $(tabHtml).appendTo(tabs);
    },
    openTab: function (options) {
        var div = BigUtil.createTab(options);
        div.data('tab-options', options);
        div.load(options.url, options.params, function () {
            if (options.fn) {
                options.fn(div);
                return;
            }
            BigUtil.initInputor({
                inputor: div.find('[data-biginputor],[data-app-inputor]')
            });
            BigUtil.initCombo({
                combo: div.find('[data-bigcombo-url],[data-bigcombo]')
            });
            $('form[data-bigform-url]').each (function () {
            	var form = $(this);
            	// 设置提交按钮点击事件
            	$(this).on ('click', 'button[data-bigform-submit]', function () {
            		var btn = $(this);
            		BigUtil.ajaxForm ({
            			form : form,
            			successFn : function () {
            				// 按钮点击之后提交表单，成功后的后续动作
                    		var action = btn.attr('data-bigform-submit');
                    		BigUtil.closeTab();//关闭当前tab
                    		if (action == 'refreshTab') {
                    			BigUtil.refreshTab();//刷新最近的一个tab
                    		} else if (action) {
                    			eval(action);
                    		}
            			}
            		});
            	});
            	// 设置取消按钮点击事件
            	$(this).on ('click', 'button[data-bigform-cancel]', function () {
            		BigUtil.closeTab();//关闭当前tab
            	});
            });
            
        });
    },
    refreshTab: function (params) {
        var div = $('div[id^=divBigContentTab_]:last');
        var options = div.data('tab-options');
        if (options) {
        	 BigUtil.clone(options.params, params);
            div.load(options.url, options.params, options.fn);
        } else {
        	var contentDiv = div.find('div[data-menu-autoload=true]');
        	if (contentDiv.length > 0) {
        		params = BigUtil.clone(BigUtil.parseData(contentDiv, 'data-menu-'), params);
            	contentDiv.load (params.url, params);
        	} else {
        		location.reload();
        	}
        }
    },
    /**
     * @param jq 触发关闭的jq对象
     */
    closeTab: function (jq) {
        var tabcontent;
        var tabheader;
        if (jq) {
            tabcontent = jq.parents('#divBigContent .tab-content .tab-pane');
            if (tabcontent.length == 0) {
                tabheader = jq.parents('#divBigContent .nav-tabs li');
                if (tabheader.length == 0) {
                    return;
                }
                tabcontent = $(tabheader.find('a').attr('href'));
            } else {
                tabheader = $('a[href="#' + tabcontent.attr('id') + '"]').parent();
            }
        } else {
            tabcontent = $('#divBigContent .nav-tabs li.active');
            tabheader = $('#divBigContent .tab-content .tab-pane.active');
        }
        tabcontent.remove();
        tabheader.remove();
        if ($('#divBigContent .nav-tabs li.active').length == 0) {
            $('#divBigContent .nav-tabs li:last').addClass('active');
            $('#divBigContent .tab-content .tab-pane:last').addClass('active');
        }
    },
    parseArray: function (str, split) {
        if (BigUtil.isEmpty(split)) {
            split = ",";
        }
        if (BigUtil.isEmpty(str)) {
            return [];
        }
        return str.split(split);
    },
    showMainModal: function (opts) {
        var options = BigUtil.clone({
            title: '提示',
            html: '许多话没向你说'
        }, opts);
        var modal = $('[data-bigmodal-main]');
        if (options.modalAttr) {
            modal = $('[' + options.modalAttr + ']');
            if (modal.length == 0) {
                modal = $('[data-bigmodal-main]').clone().appendTo('body').removeAttr('data-bigmodal-main').attr(options.modalAttr, true);
            }
        }
        modal.find('.modal-title').text (options.title);
        if (options.fieldsHtml) {
            modal.find('.modal-body form').html (options.fieldsHtml);
        } else {
            modal.find('.modal-body').html (options.html);
        }
        modal.modal('show');
        if (options.fn) {
            options.fn(modal.find('button.fa-edit'), modal);
        }
        return modal;
    },
    parseModalData: function (modal, prefix) {
        var data = {};
        var selector = 'input,select,textarea';
        if (prefix) {
            selector = 'input[name^="' + prefix + '"],select[name^="' + prefix + '"],textarea[name^="' + prefix + '"]';
        }
        modal = BigUtil.getObject(modal);
        modal.find(selector).each(function () {
            var type = $(this).attr('type');
            var name = $(this).attr('name');
            var value = $(this).val();
            if ((type == 'radio' || type == 'checkbox') && !$(this).is(':checked')) {
                return;
            }
            if (data[name] == undefined) {
                data[name] = value;
            } else {
                data[name] += ',' + value;
            }
        });
        return data;
    },
    containsValue: function (values, value) {
        if (BigUtil.isEmpty(values) || BigUtil.isEmpty(value)) {
            return false;
        }
        if (!(values instanceof Array)) {
            values = values.toString().split(',');
        }
        for (var i = 0; i < values.length; i++) {
            if (values[i] == value) {
                return true;
            }
        }
        return false;
    },
    setInputValue: function (input, json, name) {
        var type = input.attr('type');
        if (BigUtil.isEmpty(name)) {
            name = input.attr('name');
        }
        if (BigUtil.isEmpty(json[name])) {
            return;
        }
        var value = input.attr('value');
        if (type == 'radio') {
            if (BigUtil.containsValue(json[name], value)) {
                input.prop('checked', true);
                input.click();
            }
        } else if (type == 'checkbox') {
            if (BigUtil.containsValue(json[name], value)) {
                input.prop('checked', true);
            } else {
                input.prop('checked', false);
            }
        } else {
            input.val(json[name]);
            input.attr('data-bigmodal-value', json[name]);
        }
    },
    /**
     * @param modal
     * @param json {name:, value:}
     */
    loadModalData: function (modal, json) {
        modal.find('input,select,textarea').each(function () {
            BigUtil.setInputValue($(this), json);
        });
    },
    regexMobile : /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/,
    checkIDCard : function(idcode){
	    // 加权因子
	    var weight_factor = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
	    // 校验码
	    var check_code = ['1', '0', 'X' , '9', '8', '7', '6', '5', '4', '3', '2'];

	    var code = idcode + "";
	    var last = idcode[17];//最后一位

	    var seventeen = code.substring(0,17);

	    // ISO 7064:1983.MOD 11-2
	    // 判断最后一位校验码是否正确
	    var arr = seventeen.split("");
	    var len = arr.length;
	    var num = 0;
	    for(var i = 0; i < len; i++){
	        num = num + arr[i] * weight_factor[i];
	    }
	    
	    // 获取余数
	    var resisue = num%11;
	    var last_no = check_code[resisue];

	    // 格式的正则
	    // 正则思路
	    /*
	    第一位不可能是0
	    第二位到第六位可以是0-9
	    第七位到第十位是年份，所以七八位为19或者20
	    十一位和十二位是月份，这两位是01-12之间的数值
	    十三位和十四位是日期，是从01-31之间的数值
	    十五，十六，十七都是数字0-9
	    十八位可能是数字0-9，也可能是X
	    */
	    var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

	    // 判断格式是否正确
	    var format = idcard_patter.test(idcode);

	    // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
	    return last === last_no && format ? true : false;
	},
    validateForm : function (form) {

        var lastInvalid;// 最后一个没有验证通过的控件，需要设置其获得焦点
    	function showMsg (input, msg) {
    		var formGroup = input.parents('.form-group:first');
    		formGroup.append('<span class="control-label text-red">' + msg + ' </span>');
            if (input.attr('type') == 'hidden') {
                lastInvalid = formGroup.find(':text,textarea');
            } else {
                lastInvalid = input;
            }
    	}
    	
        form = BigUtil.getObject(form, 'form');
        // 校验表单内容（必填）
        // 删除告警提示
        form.find('.control-label.text-red').remove();
        // 增加告警提示
        form.find('[data-app-required]').each (function () {
            var formGroup = $(this).parents('.form-group:first');
            // 获取告警消息内容
            let msg = $(this).attr('data-app-required');
            if (BigUtil.isEmpty(msg)) {
                msg = $(this).attr('placeholder');
                if (BigUtil.isEmpty(msg)) {
                    msg = formGroup.find('label').text().trim();
                    if (BigUtil.isEmpty(msg)) {
                        msg = '必填！';
                    } else {
                        msg = msg + '为必填！';
                    }
                } else {
                    msg = msg + '为必填！';
                }
            }
            let multipleHidden = formGroup.find('[data-bigmultiple]');
            if (multipleHidden.length > 0 && !$(this).is("[type=hidden]")) {
                if (!BigUtil.isEmpty(multipleHidden.val()) && (BigUtil.isEmpty($(this).val()) || ($(this).is('[data-app-filetype]') && BigUtil.isEmpty($(this).attr('data-value'))))) {
                    // 增加警告提示
                    showMsg ($(this), msg);
                }
            } else if (BigUtil.isEmpty($(this).val()) || (formGroup.attr('data-app-filetype') == 'image' && $(this).val() == '0')) {
                // 增加警告提示
            	showMsg ($(this), msg);
            }

        });
        form.find(':text[data-app-regex]').each (function () {
            var formGroup = $(this).parents('.form-group:first');
            $(this).val ($(this).val().trim());
            if (BigUtil.isEmpty($(this).val())) {
            	return;
            }
            var regex = $(this).attr('data-app-regex');
            var label = formGroup.find('label:first').text();
            if (regex == 'mobile') {
            	regex = BigUtil.regexMobile;
            	if (BigUtil.isEmpty(label)) {
            		label = '手机号';
            	}
            } else if (regex == 'IDCard') {
            	regex = /^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$/;
            	if (BigUtil.isEmpty(label)) {
            		label = '身份证号';
            	}
            } else if (regex.indexOf ('same:') == 0) {
            	if (regex.substring(5) != $(this).val()) {
            		// 增加警告提示
                	showMsg ($(this), '请正确输入如下内容：' + regex.substring(5));
            	}
            	return;
            } else if (regex == 'email') {
            	regex = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
            	if (BigUtil.isEmpty(label)) {
            		label = '电子邮箱';
            	}
            } else {
                regex = eval (regex);
            }
            if (!regex.test($(this).val())) {
            	// 增加警告提示
            	showMsg ($(this), label + '格式不正确！');
            }
        });
        // 如果有告警提示，表示验证失败，不再提交表单
        if (form.find('.control-label.text-red').length > 0) {
            lastInvalid.focus();
            console.log ('validate form fields failed.');
            return false;
        }
        return true;
    },
    /**
     *
     * @param opts 参考$.ajax的入参说明，并增加了params（参数）/form/formSelector（表单选择器）/formType(form|modal)/errorFn（失败回调）/successFn（成功回调）/completeFn（调用完成）等参数
     */
    ajaxForm: function (opts) {
        var options = BigUtil.clone({
            type: "post",
            dataType: "json",
            error: function (xmlHttpRequest, error, errorObject) {
                if (opts.errorFn) {
                    opts.errorFn(error);
                } else {
                    alert('提交失败：' + error);
                }
            },
            success: function (json) {
            	if (opts.completeFn) {
                    opts.completeFn(json);
                } else if (json.success && opts.successFn) {
                    opts.successFn(json);
                } else if (!json.success && opts.errorFn) {
                    opts.errorFn(json);
                } else {
                    alert(json.msg);
                }
            }
        }, opts);

        var form = opts.form;
        if (opts.formSelector) {
            form = $(opts.formSelector);
        }
        if (!form) {
        	console.log ('Form not found!');
        	return;
        }
        
        if(!options.url) {
        	options.url = form.attr('data-bigform-url');
        }
        
        if (form.attr('enctype') == "multipart/form-data") {
        	opts.file = true;
        }
        
        $('[data-app-ckeditor]').each(function () {
            var formGroup = $(this);
            var ta = formGroup.find('textarea');
            var ckeditor = CKEDITOR.instances[ta.attr('id')];
            ta.val(ckeditor.getData());
        });
        // 校验表单内容（必填）
        if (!BigUtil.validateForm(form)) {
            return;
        }
        // 包含文件时
        if (opts.file) {
            BigUtil.clone(options, {
                cache: false,
                processData: false,
                contentType: false
            });
            options.data = new FormData(form[0]);
            for (var key in opts.params) {
                options.data.append(key, opts.params[key]);
            }
            for (var key of options.data.keys()) {
            	var vals = options.data.getAll(key);
            	if (vals.length > 1) {
            		options.data.set(key, vals.join(','));
            	}
            }
        } else {// 不包含文件时
            if (options.formType == 'modal') {
                options.data = BigUtil.clone(BigUtil.parseModalData(form), opts.params);
            } else {
                options.data = BigUtil.mergeFormData(form.serializeArray(), opts.params);
                var d = {};
                for (var i = options.data.length - 1; i >= 0; i--) {
                    var key = options.data[i].name;
                    if (d[key] == undefined) {
                        d[key] = options.data[i].value;
                    } else {
                        d[key] += ',' + options.data[i].value;
                    }
                }
                options.data = d;
            }
        }
        $.ajax(options);
    },
    /**
     * 表单中的objectSelector/objectInputor控件已选记录的按钮
     * @param value
     * @param name
     * @returns {string}
     */
    createRelatedNameButtons: function (value, name, type) {
        return '<button type="button" data-app-value="' + value + '" data-app-type="' + type + '" class="btn btn-xs btn-times-circle margin-r-5">' + name + '</button>';
    },
    /**
     *
     * @param opts inputor/inputorSelector/params/searchUrl/autoLoad/dataUrl
     */
    initInputor: function (opts) {
        var options = BigUtil.clone({
            autoLoad: true,
            inputorSelector: '[data-biginputor]'
        }, opts);
        var inputor = options.inputor;
        if (!inputor) {
            inputor = $(options.inputorSelector);
        }
        // objectInputor
        inputor.each(function () {
            var hidden = $(this);
            if (hidden.attr('data-app-readonly') != 'true') {
                // 设置按钮点击事件
                hidden.next().on('click', 'button', function () {
                    // 按钮点击时，会删除hidden中对应的值，并删除按钮元素
                    var val = $(this).attr('data-app-type') + ':' + $(this).attr('data-app-value');
                    var values = BigUtil.parseArray(hidden.val());
                    for (var i = values.length - 1; i >= 0; i--) {
                        if (values[i] == val) {
                            values.splice(i, 1);
                        }
                    }
                    hidden.val(values.join(','));
                    $(this).remove();
                });
            }
            // 视图属性id
            var propertyId = hidden.attr('name');
            // 文本域事件设置
            var textfield = hidden.next().find('input');
            var dataList = $('#' + textfield.attr('list'));
            var err = 'err@@##'; // 错误id

            function createOption(optionData) {
                var option = $('<option />').appendTo(dataList);
                option.data('optionData', optionData);
                option.attr('value', '- ' + optionData.name);
            }

            var params = BigUtil.clone({
                propertyId: propertyId
            }, BigUtil.parseData(hidden, "data-biginputor-"));
            params = BigUtil.clone(params, BigUtil.parseData(hidden, "data-app-"));
            params = BigUtil.clone(params, options.params);

            // 当dataList中选项被选中时调用
            function dataListSelected() {
                var content = textfield.val().trim().replace('\'', '');
                // 获取datalist上对应的option元素
                var opt = dataList.find('option[value=\'' + content + '\']');
                if (opt.length == 0) {
                    // 清空文本域内容
                    textfield.val('');
                    return;
                }

                var idVal = opt.data('optionData').value;
                if (idVal == err) {
                    // 清空文本域内容
                    textfield.val('');
                    return;
                }
                var nameVal = opt.data('optionData').name;
                var typeVal = opt.data('optionData').type;
                // 判断当前选项是否已经选择
                var selected = false;
                textfield.siblings('button').each(function () {
                    if ($(this).attr('data-app-value') == idVal && $(this).attr('data-app-type') == typeVal) {
                        selected = true;
                    }
                });
                // 当前选项已经选择则返回
                if (selected) {
                    // 清空文本域内容
                    textfield.val('');
                    return;
                }
                // 如果是单选，则删除之前的按钮
                if (hidden.attr('data-app-selectorsingle') == 'true') {
                    textfield.siblings('button').remove();
                    // 设置隐藏域字段
                    hidden.val(typeVal + ':' + idVal);
                } else {
                    // 设置隐藏域字段
                    if (BigUtil.isEmpty(hidden.val())) {
                        hidden.val(typeVal + ':' + idVal);
                    } else {
                        hidden.val(hidden.val() + ',' + typeVal + ':' + idVal);
                    }
                }
                // 创建按钮，用于显示选中的option中的内容
                var btn = BigUtil.createRelatedNameButtons(idVal, nameVal, typeVal);
                // 将按钮设置到文本域之前
                textfield.before(btn);
                // 清空文本域内容
                textfield.val('');
            };


            // textfield内容改变
            textfield.bind("input propertychange", function () {
                var content = textfield.val().trim().replace('\'', '');
                if (content == '') {
                    return;
                }
                if (content.startsWith('-')) {
                    dataListSelected();
                    return;
                }
                var searchUrl = hidden.attr('data-biginputor-searchurl');
                if (BigUtil.isEmpty(searchUrl)) {
                    searchUrl = options.searchUrl;
                }
                if (BigUtil.isEmpty(searchUrl)) {
                    searchUrl = '/meta/objectinputor/list';
                }
                var data = BigUtil.clone({searchContent: content}, params);
                data = BigUtil.mergeFormData(textfield.parents('form:first').serializeArray(), data);
                $.post(searchUrl, data, function (json) {
                    if (json.success) {
                        dataList.empty();
                        if (json.content.length == 0) {
                            var data = {
                                value: err,
                                name: '未查询到"' + content + '"'
                            };
                            createOption(data);
                            return;
                        }
                        for (var i = 0; i < json.content.length; i++) {
                            createOption(json.content[i]);
                        }
                    } else {
                        var data = {
                            value: err,
                            name: '查询"' + content + '"时出错:' + json.msg
                        };
                        createOption(data);
                    }
                });
            });

            // 如果不是自动加载，则退出
            if (!options.autoLoad) {
                return;
            }
            // 加载名称按钮
            var data = BigUtil.clone({value: hidden.val()}, params);
            if (BigUtil.isEmpty(data.value) && BigUtil.isEmpty(data.keyValue)) {
                return;
            }
            var dataUrl = hidden.attr('data-biginputor-dataurl');
            if (BigUtil.isEmpty(dataUrl)) {
                dataUrl = options.dataUrl;
            }
            if (BigUtil.isEmpty(dataUrl)) {
                dataUrl = '/meta/objectinputor/value';
            }
            $.post(dataUrl, data, function (json) {
                if (json.success) {
                    if (json.content && json.content.length > 0) {
                        hidden.val('');
                        for (var i = json.content.length - 1; i >= 0; i--) {
                            // 创建按钮，用于显示选中的option中的内容
                            var btn = BigUtil.createRelatedNameButtons(json.content[i].value, json.content[i].name, json.content[i].type);
                            // 将按钮设置到文本域之前
                            textfield.before(btn + '&nbsp;');
                            // 设置隐藏域字段
                            if (BigUtil.isEmpty(hidden.val())) {
                                hidden.val(json.content[i].type + ':' + json.content[i].value);
                            } else {
                                hidden.val(hidden.val() + ',' + json.content[i].type + ':' + json.content[i].value);
                            }
                        }
                    }
                }
            });
        });
    },
    initDictionaryCombo: function (opts) {
        var formGroups = BigUtil.getObject(opts.dictionaryCombo, '[data-app-choicetype=combo]');
        formGroups.each (function () {
            var formGroup = $(this);
            if (formGroup.find('select option[value!=""]').length > 0) {
                return;
            }
            var params = BigUtil.parseData (formGroup, 'data-dictionary-');
            $.post ('/meta/dictionary', params, function (json) {
                if (json.success) {
                    for (var i = 0; i < json.content.length; i ++) {
                        var dictionary = json.content[i];
                        var choice = $("<option></option>").appendTo (formGroup.find('select'));
                        choice.attr('value', dictionary.value);
                        choice.text(dictionary.name);
                        choice.attr('selected', dictionary.active);
                    }
                }
            });
        });
    },
    initDictionaryRadio: function (opts) {
        var formGroups = BigUtil.getObject(opts.dictionaryRadio, '[data-app-choicetype=radio]');
        formGroups.each (function () {
            var formGroup = $(this);
            var params = BigUtil.parseData (formGroup, 'data-dictionary-');
            $.post ('/meta/dictionary', params, function (json) {
                if (json.success) {
                    for (var i = 0; i < json.content.length; i ++) {
                        var dictionary = json.content[i];
                        var html = [
                            '<div class="col-sm-2">',
                            '<div class="radio">',
                            '<label>',
                            '<input type="radio">',
                            dictionary.name,
                            '</label>',
                            '</div>',
                            '</div>'].join('');
                        var choice = $(html).appendTo (formGroup.find('.row'));
                        choice.find('input').attr('value', dictionary.value);
                        choice.find('input').attr('name', formGroup.attr('data-app-vpid'));
                        choice.find('input').attr('checked', dictionary.active);
                        choice.find('input').attr('disabled', formGroup.attr('data-app-readonly') == 'true');
                    }
                }
            });
        });
    },
    initDictionaryCheckbox: function (opts) {
        var formGroups = BigUtil.getObject(opts.dictionaryCheckbox, '[data-app-choicetype=checkbox]');
        formGroups.each (function () {
            var formGroup = $(this);
            var params = BigUtil.parseData (formGroup, 'data-dictionary-');
            $.post ('/meta/dictionary', params, function (json) {
                if (json.success) {
                    for (var i = 0; i < json.content.length; i ++) {
                        var dictionary = json.content[i];
                        var html = [
                            '<div class="col-sm-2">',
                            '<div class="checkbox">',
                            '<label>',
                            '<input type="checkbox">',
                            dictionary.name,
                            '</label>',
                            '</div>',
                            '</div>'].join('');
                        var choice = $(html).appendTo (formGroup.find('.row'));
                        choice.find('input').attr('value', dictionary.value);
                        choice.find('input').attr('name', formGroup.attr('data-app-vpid'));
                        choice.find('input').attr('checked', dictionary.active);
                        choice.find('input').attr('disabled', formGroup.attr('data-app-readonly') == 'true');
                    }
                }
            });
        });
    },
    /**
     * combo元素上属性：data-bigcombo/data-bigcombo-url/data-bigcombo-autoload/data-bigcombo-target/data-bigmodal-value
     * @param opts combo/comboSelector/params/url
     */
    initCombo: function (opts) {
        var options = BigUtil.clone({
            comboSelector: '[data-bigcombo]'
        }, opts);
        var c = options.combo;
        if (!c) {
            c = $(options.comboSelector);
        }

        function createOption(combo, name, value) {
            if (BigUtil.isEmpty(value)) {
                combo.append('<option value>' + name + '</option>');
            } else {
                combo.append('<option value="' + value + '">' + name + '</option>');
                if (value == combo.attr('data-bigmodal-value')) {
                    combo.val(value);
                }
            }
        }

        function loadData(combo) {
            var params = BigUtil.clone(BigUtil.parseData(combo, 'data-bigcombo-'), options.params);
            $.post(params.url, params, function (json) {
                if (json.success) {
                    if (json.content && json.content.length > 0) {
                        combo.empty();
                        createOption(combo, '请选择...');
                        for (var i = 0; i < json.content.length; i++) {
                            var o = json.content[i];
                            createOption(combo, o.name, o.value);
                        }
                    } else {
                        combo.empty();
                        createOption(combo, '暂无数据...');
                    }
                } else {
                    combo.empty();
                    createOption(combo, json.msg);
                }
            });
        }

        c.each(function () {
            var combo = $(this);
            var top = combo.parents('.modal:first');
            if (top.length == 0) {
                top = combo.parents('form:first');
            }
            // 自动加载
            var autoLoad = opts.autoLoad;
            if (autoLoad == undefined) {
                autoLoad = combo.is('[data-bigcombo-autoload]');
            }
            if (autoLoad) {
                var targetData = $(this).attr('data-bigcombo-target');
                if (!BigUtil.isEmpty(targetData)) {
                    var targets = targetData.split(',');
                    for (var i = 0; i < targets.length; i++) {
                        // targets[i]格式：name:submitname或者name，submitname是提交到request中的key，如果没有则使用name
                        var names = targets[i].split(':');
                        var val = top.find('[name=' + names[0] + ']').attr('data-bigmodal-value');
                        if (BigUtil.isEmpty(val)) {
                            continue;
                        }
                        combo.attr('data-bigcombo-' + names[names.length - 1], val);
                    }
                }
                loadData(combo);
            }
            var name = combo.attr('name');
            // 寻找需要联动的combo
            var triggedCombos = [];
            top.find('select[data-bigcombo-target]').each(function () {
                var targets = $(this).attr('data-bigcombo-target').split(',');
                for (var i = 0; i < targets.length; i++) {
                    if (targets[i] == name) {
                        triggedCombos.push({
                            combo: $(this),
                            name: name
                        });
                    } else if (targets[i].startsWith(name + ':')) {
                        triggedCombos.push({
                            combo: $(this),
                            name: targets[i].split(':')[1]
                        });
                    }
                }
            });
            combo.change(function () {
                for (var i = 0; i < triggedCombos.length; i++) {
                    var triggedCombo = triggedCombos[i].combo;
                    var key = 'data-bigcombo-' + triggedCombos[i].name;
                    triggedCombo.attr(key, combo.val());
                    loadData(triggedCombo);
                }
            });
        });
    },
    /**
     * @param opts multiple/init/bindEvents/add/remove/refreshValue
     */
    initMultiple: function (opts) {
        var hiddens = BigUtil.getObject(opts.multiple, '[data-bigmultiple]');

        function getInputs (hidden) {
            return hidden.siblings('.input-group').not('.bigmultiple-image');
        }

        function readonly (hidden) {
            return BigUtil.hasAttr(hidden, 'data-bigmultiple-readonly');
        }

        /**
         * bigmultiple控件初始化时调用次方法
         * @param hidden 最终用于提交数据的隐藏域
         */
        function init (hidden) {
        	var data = JSON.parse(hidden.val()).filter(row => JSON.stringify(row) !== '{}');
            var inputGroups = getInputs(hidden);
            if (inputGroups.length == 1) {
        		for (var j = 0; j < data.length - 1; j ++) {
                    // 添加到form-group
                    inputGroups.eq(0).clone().insertAfter(inputGroups.eq(0));
        		}
        	}
            // 重新获取input-group
            inputGroups = getInputs(hidden);
            // 设置input-group值
            for (var i = 0; i < data.length; i ++) {
                var row = data[i];
                // 设置值
                var inputGroup = inputGroups.eq(i);
                var fields = inputGroup.children(':not(.bigmultiple-btn,:disabled)');
                for (var j = 0; j < fields.length; j ++) {
                    var field = fields.eq(j);
                    if (field.is(":disabled")) {
                        continue;
                    }
                    if (field.hasClass('bigmultiple-yyyy-mm')) {
                        field = field.find("input");
                    }
                    let val = row[field.attr('name')];
                    if (field.attr('data-app-filetype')) {
                        field.attr('data-value', val);
                        if (!BigUtil.isEmpty(val)) {
                            $('<div class="input-group bigmultiple-image"><img src="' + val + '"/></div>').insertAfter(field.parent());
                        }
                    } else {
                        field.val(val);
                    }
                }
            }
        }

        /**
         * bigmultiple 当删除、或者字段值被改变时，调用此方法
         * @param hidden 最终用于提交数据的隐藏域
         * @param field 控件内容的改变，触发更新hidden事件
         */
        function refreshValue (hidden, field) {
        	var data = [];
        	// 将表单验证的警告提示删除
			hidden.parent().find('.control-label.text-red').remove();
			// 处理每一行控件
            getInputs(hidden).each(function (index) {
                var inputGroup = $(this);
                // 将索引按照顺序设置
                inputGroup.find('[data-bigmultiple-index]').val(index + 1);
                // 获取一行数据
                var row = {};
                var fields = inputGroup.children(':not(.bigmultiple-btn,:disabled)');
                for (var i = 0; i < fields.length; i ++) {
                	var field = fields.eq(i);
                    if (field.hasClass('bigmultiple-yyyy-mm')) {
                        field = field.find("input");
                    }
                    if (!field.attr('name')) {
                        continue;
                    }
                	var fieldVal;
                	if (field.attr('data-app-filetype')) {
                        fieldVal = field.attr('data-value');
                    } else {
                        fieldVal = field.val();
                    }
                    var type = field.attr('data-app-fieldtype');
                	if (BigUtil.isEmpty(type)) {
                		row[field.attr('name')] = fieldVal;
                	} else {
                		type = type.split(':', 2);
                		if (type[0] == 'String') {
                			row[field.attr('name')] = fieldVal;
                		} else {
                			row[field.attr('name')] = eval('parse' + type[0] +  '(fieldVal)');
                			if (isNaN(row[field.attr('name')])) {
                				var alert = type.length == 1 ? '字段类型为' + type[0] + '哟' : type[1];
                                hidden.parent().find('.control-label.text-red').remove();
                				hidden.parent().append('<span class="control-label text-red">' + alert + '</span>');
                			}
                		}
                	}
                }
                data.push(row);
            });
            // 设置所有数据到hidden上
            hidden.val(JSON.stringify(data));
        }

        function show (isImage, url) {
        	if (isImage) {
				BigUtil.showMainModal({
            		title:'显示',
            		html: '<img src="' + url + '" style="max-width:100%;max-height=100%"></img>'
            	});
			} else {
				window.open(url);
			}
        }
        
        function attachShowEvent (component) {
        	 // 绑定事件
        	component.find('[data-app-filetype=show]').click (function () {
    	        var url = $(this).next().attr('data-value');
    	        if (BigUtil.isEmpty(url)) {
    	        	return;
    	        }
    	        var regex = /.*\.(gif|jpg|jpeg|png)$/i;
    	        if (url.indexOf('/meta/file/') == 0) {
    	        	$.post('/meta/file/json/' + url.substring('/meta/file/'.length), {}, function (json) {
    	        		if (json.success) {
    	        			show (regex.test('xx.' + json.content.type), url);
    	        		} else {
    	        			alert(json.msg);
    	        		}
    	        	});
    	        } else {
    	    		show (regex.test(url), url);
    	        }
    	    });
        }
        
	    // 设置控件事件
	    function attachEvents (component, hidden) {
	    	// 当字段内容变化时，更新hidden的value值
            component.find(':text').bind("input propertychange", function () {
                if (opts.refreshValue) {
                    opts.refreshValue(hidden, $(this));
                } else {
                    refreshValue(hidden, $(this));
                }
            });
            component.find(':text,select').change(function () {
                if (opts.refreshValue) {
                    opts.refreshValue(hidden, $(this));
                } else {
                    refreshValue(hidden, $(this));
                }
            });
            // 上传文件
            component.find('[data-app-filetype=file]').click (function () {
                var field = $(this);
                if (opts.refreshValue) {
                    opts.refreshValue(hidden, $(this));
                } else {
                    var modal = $('[data-bigupload]');
                    modal.modal ('show');
                    modal.find('input[type=file]').val('');
                    modal.find('button:last').unbind();
                    modal.find('button:last').click (function () {
                        BigUtil.ajaxForm({
                            url : '/meta/file',
                            file : true,
                            form : modal.find('form:first'),
                            success : function (json) {
                                if (json.success) {
                                    let fileUrl = '/meta/file/' + json.content.id;
                                    field.attr('data-value', fileUrl);
                                    if (field.parent().next().is('.bigmultiple-image')) {
                                        field.parent().next().find('img').attr('src', fileUrl);
                                    } else {
                                        $('<div class="input-group bigmultiple-image"><img src="' + fileUrl + '"/></div>').insertAfter(field.parent());
                                    }
                                    refreshValue(hidden, $(this));
                                    modal.modal ('hide');
                                } else {
                                    alert(json.msg);
                                }
                            }
                        });
                    });
                }
            });
	    }
	    
        hiddens.each(function () {
            var hidden = $(this);
            // 初始化控件
            if (!BigUtil.isEmpty(hidden.val())) {
                // 初始化
                if (opts.init) {
                    opts.init(hidden);
                } else {
                	init(hidden);
                }
            } else if (readonly(hidden)) {
                getInputs(hidden).eq(0).remove();
            }
            
            attachShowEvent(hidden.parent());
            // 初始化时间控件
            hidden.parent().find('[data-date-format="yyyy-mm"]').datetimepicker({
                weekStart: 1,
                todayBtn:  1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 4,
                minView : 3,
                forceParse: 0,
                showMeridian: 1
            });
            if (readonly(hidden)) {
                hidden.parent().find('.bigmultiple-yyyy-mm .input-group-addon').unbind();
                hidden.parent().find(':text').attr('disabled', true);
                hidden.parent().find(':button[data-app-filetype=file]').attr('disabled', true);
                hidden.parent().find('select').attr('disabled', true);
                // 删除+-按钮
                hidden.parent().find('.bigmultiple-btn span').addClass('disabled');
            }

            // 绑定用户输入字段的事件
            if (opts.bindEvents) {
                opts.bindEvents(hidden);
            } else if (!readonly(hidden)) {
                attachEvents(hidden.parent(), hidden);
            }

            if (readonly(hidden)) {
                hidden.parent().find('.bigmultiple-btn span').addClass('disabled');
                return;
            }
            // 添加
            hidden.parent().on('click', '.bigmultiple-btn:even', function () {
                if (opts.add) {
                    opts.add(hidden);
                } else {
                    // 将input-group克隆后添加到form-group最后
                    var newInputGroup = $(this).parent().clone().insertAfter(hidden.siblings('.input-group:last'));
                    newInputGroup.find('.form-control').not(':button,:disabled').val('');
                    newInputGroup.find('[data-app-filetype]').removeAttr('data-value');
                    newInputGroup.find('[data-bigmultiple-index]').val(hidden.siblings('.input-group').length);
                    attachEvents(newInputGroup, hidden);
                    attachShowEvent(newInputGroup);
                    newInputGroup.find('[data-date-format="yyyy-mm"]').datetimepicker({
                        weekStart: 1,
                        todayBtn:  1,
                        autoclose: 1,
                        todayHighlight: 1,
                        startView: 4,
                        minView : 3,
                        forceParse: 0,
                        showMeridian: 1
                    });
                    if (opts.afterAdd) {
                    	opts.afterAdd(hidden, newInputGroup);
                    }
                }
            });
            // 删除
            hidden.parent().on('click', '.bigmultiple-btn:odd', function () {
                if (opts.remove) {
                    opts.remove(hidden);
                } else {
                    // 将input-group删除
                    if (hidden.siblings('.input-group').not('.bigmultiple-image').length > 1) {
                    	if (opts.beforeRemove) {
                    		opts.beforeRemove(hidden, $(this).parent());
                        }
                        if ($(this).parent().next().is('.bigmultiple-image')) {
                            $(this).parent().next().remove();
                        }
                        $(this).parent().remove();
                        if (opts.refreshValue) {
                            opts.refreshValue(hidden);
                        } else {
                            refreshValue(hidden);
                        }
                    } else {
                        $(this).parent().find('.form-control').not(':button,:disabled').val('');
                        if ($(this).parent().next().is('.bigmultiple-image')) {
                            $(this).parent().next().remove();
                        }
                        hidden.val('');
                    }
                }
            });
        });
    },
    /**
     * bigmultiple的Map实现
     */
    initMap: function (opts) {
        var options = BigUtil.clone({
            init: function (hidden) {
                var data = JSON.parse(hidden.val());
                var inputGroup = hidden.siblings('.input-group:last');
                for (var key in data) {
                    // 克隆一个input-group
                    if (inputGroup.length == 0 || !BigUtil.isEmpty(inputGroup.children().eq(0).val())) {
                        inputGroup = hidden.next().clone();
                        // 添加到form-group
                        inputGroup.appendTo(hidden.parent());
                    }
                    // 设置其第一个字段为key，另一个为value
                    inputGroup.children().eq(0).val(key);
                    inputGroup.children().eq(1).val(data[key]);
                }
            },
            refreshValue: function (hidden) {
                // 当字段内容变化时，更新hidden的value值
                var data = {};
                hidden.siblings('.input-group').each(function () {
                    var inputGroup = $(this);
                    var key = inputGroup.children().eq(0).val();
                    var value = inputGroup.children().eq(1).val();
                    if (BigUtil.isEmpty(key) || BigUtil.isEmpty(value)) {
                        return;
                    }
                    data[key] = value;
                });
                hidden.val(JSON.stringify(data));
            }
        }, opts);
        BigUtil.initMultiple(options);
    },
    // {file:,}
    initFile: function (opts) {
        var formGroups = BigUtil.getObject(opts.file, 'div[data-app-filetype]');
        function createFileHtml (divFormGroup, url, fileName) {
            if (!fileName) {
                let index = url.lastIndexOf('/');
                if (index >= 0) {
                    fileName = url.substring(index + 1);
                }
            }
            divFormGroup.find('div[data-file-wrapper]').empty();
            if (divFormGroup.attr('data-app-filetype') == 'image') {
                let width = divFormGroup.find('div[data-file-wrapper]').attr('data-image-width');
                if (BigUtil.isEmpty(width)) {
                    width = "100%";
                }
                divFormGroup.find('div[data-file-wrapper]').append('<img style="max-width:' + width + ';" src="' + url + '" alt="' + fileName + '"/>');
            } else {
                divFormGroup.find('div[data-file-wrapper]').append('<a href="' + url + '" target="_blank">' + fileName + '</a>');
            }
        }
        // file
        function showFile (divFormGroup, json) {
            if (json.success) {
                createFileHtml (divFormGroup, '/meta/file/' + json.content.id, json.content.name);
            }
        }

        formGroups.each(function () {
            var formGroup = $(this);
            var modal = $('[data-bigupload]');
            // 设置上传按钮点击事件
            formGroup.find('.input-group-addon').click (function() {
                modal.modal ('show');
                // 清空已经选择的文件
                modal.find('input[type=file]').val('');
                // 设置保存按钮点击事件
                modal.find('button:last').unbind();
                modal.find('button:last').click (function () {
                    BigUtil.ajaxForm({
                        url : '/meta/file',
                        file : true,
                        form : modal.find('form:first'),
                        success : function (json) {
                            if (json.success) {
                                formGroup.find ('input[type=hidden]').val(json.content.id);
                                formGroup.find ('input[type=text]').val(json.content.name);
                                showFile (formGroup, json);
                                modal.modal ('hide');
                                if (opts.success) {
                                    opts.success(formGroup, json.content);
                                }
                            }
                        }
                    });
                });
            });
            var fileId = formGroup.find('input[type=hidden]').val();
            if (fileId == '0' || fileId == '' || fileId == undefined) {
                return;
            }
            if (fileId.indexOf('/') >= 0) {
                createFileHtml(formGroup, fileId);
            } else {
                $.post ('/meta/file/json/' + fileId, {}, function (json) {
                    showFile (formGroup, json);
                });
            }
        });
    },
    initDistrict: function (opts) {
        let provinceSelect = $('#' + opts.id + '-province');
        let required = (provinceSelect.parent().find('[data-app-required]').length > 0);
        let citySelect = $('#' + opts.id + '-city');
        let hidden = provinceSelect.prev();
        let value = opts.initValue;
        if (BigUtil.isEmpty(value)) {
            value = hidden.val();
        } else {
            hidden.val(value);
        }
        let provinceValue = '';
        let cityValue = '';
        if (!BigUtil.isEmpty(value)) {
            provinceValue = value.split(',')[0];
            cityValue = value.split(',')[1];
        }

        function change () {
            if (provinceSelect.val() == '') {
                hidden.val('');
                citySelect.val('');
            } else {
                hidden.val(provinceSelect.val() + ',' + citySelect.val());
            }
        }
        // 选择省的事件
        provinceSelect.change(function () {
            if (provinceSelect.val() == '') {
                return;
            }
            $.post('/sys/district', {province: $(this).val()}, function (json) {
                if (json.success) {
                    citySelect.empty();
                    if (!required) {
                        citySelect.append('<option value></option>');
                    }
                    for (let i = 0; i < json.content[1].length; i ++) {
                        let p = json.content[1][i];
                        citySelect.append('<option value="' + p.city + '" ' + (p.selected?'selected':'') + '>' + p.name + '</option>');
                    }
                    change();
                }
            });
        });
        // 选择地市的事件
        citySelect.change(function () {
            change();
        });
        $.post('/sys/district', {province: provinceValue, city: cityValue}, function (json) {
            if (json.success) {
                provinceSelect.empty();
                if (!required) {
                    provinceSelect.append('<option value></option>');
                }
                for (let i = 0; i < json.content[0].length; i ++) {
                    let p = json.content[0][i];
                    provinceSelect.append('<option value="' + p.province + '" ' + (p.selected?'selected':'') + '>' + p.name + '</option>');
                }
                citySelect.empty();
                if (!required) {
                    citySelect.append('<option value></option>');
                }
                for (let i = 0; i < json.content[1].length; i ++) {
                    let p = json.content[1][i];
                    citySelect.append('<option value="' + p.city + '" ' + (p.selected?'selected':'') + '>' + p.name + '</option>');
                }
                provinceSelect.val(provinceValue);
                change();
            }
        });
    }
};


$(function () {
    var t;
    // 设置下拉菜单的菜单项（有下级菜单）
    $('body').on('mouseover', 'li.bigdropdown', function () {
        $(this).siblings().removeClass('open');
        $(this).find('.dropdown-menu').css('left', '130px').css('top', '0px');
        $(this).addClass('open');
        var li = this;
        clearTimeout(t);
        t = setTimeout(function () {
            $(li).removeClass('open');
        }, 2000);
    });

    $('body').on('click', '[data-bigmodal],[data-bigmodal-selector]', function () {
        var data = BigUtil.parseData($(this), 'data-bigmodal-');
        var modal;
        if (data.selector) {
            modal = $(data.selector);
        } else {
            modal = $(this).next();
        }

        function showModal() {
            for (var key in data) {
                var field = modal.find('[name="' + key + '"]');
                field.each(function () {
                    var values = data[key].split(',');
                    var checked = false;
                    for (var i = 0; i < values.length; i++) {
                        if ($(this).val() == values[i]) {
                            checked = true;
                            break;
                        }
                    }
                    if ($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox') {
                        if ($(this).parents('.hidden').length > 0 || $(this).parents('[data-bigradio]').length == 0) {
                            if (checked) {
                                $(this).attr('checked', 'checked');
                            } else {
                                $(this).removeAttr('checked');
                            }
                        } else {
                            if (checked != $(this).is(':checked')) {
                                $(this).attr('checked', 'checked');
                                clickRadioOrCheckbox($(this));
                            }
                        }
                    } else {
                        $(this).val(data[key]);
                        if ($(this).parents('.hidden').length == 0 && $(this).parents('[data-bigradio]').length > 0) {
                            clickRadioOrCheckbox($(this));
                        }
                    }
                });
            }
            BigUtil.initInputor({
                inputor: modal.find('[data-biginputor]')
            });
            BigUtil.initCombo({
                combo: modal.find('[data-bigcombo-url],[data-bigcombo]')
            });
            modal.modal('show');
        }

        if (data.url) {
            $.post(data.url, data, function (json) {
                if (json.success) {
                    BigUtil.loadModalData(modal, json.content);
                    showModal();
                } else {
                    alert(json.msg);
                }
            });
        } else {
            showModal();
        }
    });

    // radiao或者checkbox点击
    function clickRadioOrCheckbox(input) {
        var trigger = input.attr('name');
        var triggerValue = trigger + '.' + input.val();
        var top = input.parents('.modal:first');
        var modal = true;
        if (top.length == 0) {
            top = input.parents('form:first');
            modal = false;
        }
        top.find('[data-bigradio-target]').each(function () {
            var triggerValues = $(this).attr('data-bigradio-target').split(',');
            if (input.attr('type') == 'checkbox') {
                var target = false;
                for (var i = 0; i < triggerValues.length; i++) {
                    if (triggerValues[i] == triggerValue) {
                        target = true;
                    }
                }
                if (target) {
                    $(this).toggleClass('hidden');
                    if ($(this).is(':not(.hidden)')) {// 显示时，判断下面的
                        $(this).find('[checked]').prop('checked', true);
                        $(this).find('[checked],[type=checkbox]').each(function () {
                            if ($(this).parents('[data-bigmodal]').length > 0) {
                                clickRadioOrCheckbox($(this));
                            }
                        });
                    }
                }
            } else {
                var show = false;
                var target = false;
                for (var i = 0; i < triggerValues.length; i++) {
                    if (triggerValues[i] == triggerValue) {
                        show = true;
                        target = true;
                    }
                    if (triggerValues[i].startsWith(trigger + '.')) {
                        target = true
                    }
                }
                if (target) {
                    if (show) {
                        $(this).removeClass('hidden');
                        $(this).find('[checked]').prop('checked', true);
                        $(this).find('[checked],[type=checkbox]').each(function () {
                            clickRadioOrCheckbox($(this));
                        });
                    } else {
                        $(this).addClass('hidden');
                    }
                }
            }
        });
        if (modal) {
        	top.modal('show');
        }
    }

    // radio点击时，触发显示/隐藏指定元素
    $('body').on('click', '[data-bigradio] input[type=radio]', function () {
        clickRadioOrCheckbox($(this));
    });

    // checkbox点击时，触发显示/隐藏指定元素
    $('body').on('click', '[data-bigradio] input[type=checkbox]', function () {
        clickRadioOrCheckbox($(this));
    });

    // 点击触发打开Tab页
    $('body').on('click', '[data-bigbutton-taburl]', function () {
        BigUtil.openTab({
            title: $(this).text(),
            url: $(this).attr('data-bigtab-taburl'),
            params: BigUtil.parseData($(this), 'data-bigtab-')
        });
    });

    // 点击触发json请求
    $('body').on('click', '[data-bigbutton-requesturl]', function () {
        $.post($(this).attr('data-bigbutton-requesturl'), BigUtil.parseData($(this), 'data-bigbutton-'), function (json) {
            if (json.success) {
                BigUtil.refreshTab();
            } else {
                alert(json.msg);
            }
        });
    });

});

Date.prototype.format = function(fmt)
{ //author: meizz
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}